// g++ json.cpp -o json -ljsoncpp

#include <iostream>
#include <sstream>
#include <string>
#include <memory>
#include <jsoncpp/json/json.h>

// 实现数据的序列化
bool serialize(const Json::Value &val, std::string &body){
    std::stringstream ss;
    // 先实例化一个工厂类S对象
    Json::StreamWriterBuilder swb;
    //通过工厂类对象生产派生类对象
    //Json::StreamWriter *sw = swb.newStreamWriter();
    std::unique_ptr<Json::StreamWriter> sw(swb.newStreamWriter());
    int ret = sw->write(val,&ss);
    if(ret != 0){
        std::cout << "json serialize failed!" << std::endl;
        return  false;
    }else{ 
        body = ss.str();
        return true;
    }
}
// 在 R"(...)" 中，... 是原始字符串的内容，其中的字符会被原封不动地存储在 str 中，不需要使用转义字符。

bool unserialize(const std::string &body, Json::Value &val){
    // 实例化工厂对象
    Json::CharReaderBuilder crb;
    // 生产派生类对象
    std::unique_ptr<Json::CharReader> cr(crb.newCharReader());
    std::string errs;
    //bool ret = cr->parse(body.begin(),body.end(),&val,&errs);
    bool ret = cr->parse(body.c_str(),body.c_str()+body.size(),&val,&errs);
    if(!ret){
        std::cout << "json unserialize failed !" << errs <<std::endl;
        return false;
    }else{
        return true;
    }
}
int main()
{
    const char *name = "小明";
    int age = 18;
    const char *sex = "男";
    float score[3] = {88,77.5,66};

    Json::Value student;
    student["姓名"] = name;
    student["年龄"] = age;
    student["性别"] = sex;
    // student["成绩"].append(score[0]);
    // student["成绩"].append(score[1]);
    // student["成绩"].append(score[2]);

    for(auto i:score){
        student["成绩"].append(i);
    }

    Json::Value fav;
    fav["书籍"] = "三国演义";
    fav["运动"] = "羽毛球";
    student["爱好"] = fav;
          
    std::string body;

    serialize(student,body);
    std::cout << body << std::endl;

    std::string str =R"({"姓名":"小黑", "年龄":22, "成绩":[88,99,88],
    "爱好":{"运动":"篮球","书籍":"三国演义"}})";
    Json::Value stu;
    bool ret = unserialize(str,stu);
    if(ret == false)
    return -1;
    std::cout << "姓名: " << stu["姓名"].asString() << std::endl;
    std::cout << "年龄: " << stu["年龄"].asFloat() << std::endl;
    int sz = stu["成绩"].size();
    for(int i = 0; i < sz; i++){
    std::cout << "成绩:" << stu["成绩"][i].asInt() << std::endl;
}

    // 打印爱好信息
    // std::cout << "爱好-运动："  << stu["爱好"]["运动"].asString() << std::endl;
    // std::cout << "爱好-书籍 "   << stu["爱好"]["书籍"].asString() << std::endl;

    std::cout << "爱好：" << std::endl;
    Json::Value hobbies = stu["爱好"];
    Json::Value::Members members = hobbies.getMemberNames();
    for (const auto& member : members){
    std::cout << "  " << member << " : " << hobbies[member].asString() << std::endl;
    }

    return 0;
}
